package cn.wolfcode.tieba.interceptor;

import cn.wolfcode.tieba.annotation.RequireLogin;
import cn.wolfcode.tieba.domain.User;
import cn.wolfcode.tieba.redis.service.IUserRedisService;
import cn.wolfcode.tieba.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 王金龙
 * @date 2021/1/13 18:52
 */
@Configuration
public class CheckLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserRedisService userRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 解决跨域预请求出错问题
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("token");
        // 根据token从redis中查询出user
        User user = userRedisService.getUserToken(token);

        HandlerMethod hm = (HandlerMethod) handler;
        // 只对贴了权限注解的映射方法进行判断
        if (hm.hasMethodAnnotation(RequireLogin.class)) {
            // 对user进行判空
            if (user == null) {
                // 设置编码
                response.setContentType("application/json;charset=utf-8");
                // 返回未登录提示
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }
}
